package hr.fer.zpr.nmbp.project1.dao;

import hr.fer.zpr.nmbp.project1.dao.exceptions.PrimaryKeyConstraintException;
import hr.fer.zpr.nmbp.project1.model.Bolest;
import hr.fer.zpr.nmbp.project1.model.Dijagnoza;

import java.util.List;

import com.db4o.ObjectContainer;
import com.db4o.constraints.UniqueFieldValueConstraintViolationException;
import com.db4o.query.Predicate;

public class BolestDAO {

	private ObjectContainer db;

	public BolestDAO(ObjectContainer db) {
		this.db = db;
	}

	public void save(Bolest bolest) {
		if (bolest.getNaziv() == null || bolest.getNaziv().isEmpty()) {
			throw new PrimaryKeyConstraintException(
					"Naziv bolesti ne smije biti NULL");
		}

		this.db.store(bolest);

		try {
			this.db.commit();
		} catch (UniqueFieldValueConstraintViolationException e) {
			this.db.rollback();
			throw new PrimaryKeyConstraintException(
					"Naziv bolesti već postoji u bazi podataka");
		}
	}

	public void delete(final Bolest bolest) {
		@SuppressWarnings("serial")
		List<Dijagnoza> refDijagnoze = this.db.query(new Predicate<Dijagnoza>() {
			public boolean match(Dijagnoza dijagnoza) {
				return dijagnoza.getBolesti().contains(bolest);
			}
		});
		
		for(Dijagnoza dijag : refDijagnoze){
			dijag.getBolesti().remove(bolest);
		}
		
		this.db.delete(bolest);
		this.db.commit();
	}

	public List<Bolest> load(Bolest bolestPrototype) {
		return this.db.queryByExample(bolestPrototype);
	}

	public List<Bolest> loadAll() {
		return this.db.query(Bolest.class);
	}
}
